package zj.com.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Objects;

public class LocalDownJpg {
    //java 通过url下载图片保存到本地
    public static void download(String urlString,String modelUrl,Object i) {
        long l = System.currentTimeMillis();
        if (Objects.isNull(i)){
            i=l+(long)Math.random()*100;
        }
        InputStream is = null;
        FileOutputStream os = null;
        try {
            // 构造URL
            URL url =new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs =new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            String filename ="D:\\图片下载/"+modelUrl+"/" + i +".jpg"; //下载路径及下载图片名称
            File file =new File(filename);
            os = new FileOutputStream(file,true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs,0, len);
            }
            System.out.println(i);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        download("https://img0.baidu.com/it/u=2476679390,1410592051&fm=26&fmt=auto&gp=0.jpg","1",null);
    }
}
